#include "stdafx.h"

#pragma managed
#include "EnumType.h"
#include "..\Database.h"
using namespace System::Text;
using namespace System::Diagnostics;

namespace ManagedAPI
{
	// static method
	EnumType^ EnumType::Create(const UdbEntity& entity)
	{
		Debug::Assert(entity != nullptr);
		if (entity == nullptr)
		{
			return nullptr;
		}

		char* keystr = udbEntityNameUnique(entity);
		String^ key = gcnew String(keystr);

		EnumType^ result = nullptr;
		if (mEnumList->ContainsKey(key))
		{
			result = mEnumList[key];
			Debug::Assert(result != nullptr);
		}
		else
		{
			result = gcnew EnumType(entity);
			mEnumList->Add(key, result);
		}
		return result;
	}


	void EnumType::Clear()
	{
		mEnumList->Clear();
	}

	EnumType::EnumType(const UdbEntity& entity)
		: Entity(entity)
	{

	}

	String^ EnumType::ToString()
	{
		StringBuilder^ sb = gcnew StringBuilder("enum ");
		sb->Append( this->NameLong );
		return sb->ToString();
	}

	array<Entity^>^ EnumType::GetEnumerators()
	{
		if (mEnumerators == nullptr)
		{
			UdbEntity thisEnt = GetUdbEntity();
			UdbReference* refs = nullptr;
			int unique = 1;
			int numRefs = udbEntityRefs(thisEnt, "define", "Enumerator", unique, &refs );

			if ((numRefs > 0) && (refs != nullptr))
			{
				mEnumerators = gcnew array<Entity^>(numRefs);
				for (int i = 0; i < numRefs; i++)
				{
					UdbReference ref = refs[i];
					Debug::Assert(ref != nullptr);
					UdbEntity entity = udbReferenceEntity(ref);
					Debug::Assert(entity != nullptr);
					Entity^ ent = Entity::Create(entity);
					Debug::Assert(ent != nullptr);
					mEnumerators[i] = ent;
				}
			}
			refs = nullptr;
		}
		return mEnumerators;
	}
}